package ${configs.packagePath}.utils;

import ${configs.packagePath}.exception.CustomException;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Set;
import java.util.stream.Collectors;

public class ValidateUtils {

    /**
     * 参数校验
     *
     * @param obj
     * @param validator
     */
    public static void validate(Object obj, Validator validator) throws CustomException {
        Set<ConstraintViolation<Object>> validates = validator.validate(obj);
        if (validates.size() > 0) {
            String errorMsg = validates.stream()
                    .map(value -> value.getMessage())
                    .collect(Collectors.joining(","));
            throw new CustomException(errorMsg);
        }
    }

    /**
     * 仅校验具体某个字段
     *
     * @param obj
     * @param propertyName 字段名称
     * @param validator
     *
     * @return
     */
    public static void validateProperty(Object obj, String propertyName, Validator validator) {
        Set<ConstraintViolation<Object>> validates = validator.validateProperty(obj, propertyName, Default.class);
        if (validates.size() > 0) {
            throw new ConstraintViolationException(validates);
        }
    }
}
